﻿using BCCommon;
using BCDto.Common.ErrorMessage;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Linq;

namespace BCTMSRESTful.Configs
{
    /// <summary>
    /// 用于处理模型验证的类型。
    /// </summary>
    public class RequireModelValidateAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 重写OnActionExecuting方法
        /// </summary>
        /// <param name="context">触发当前方法的上下文</param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.Filters.Any(p => p is BypassModelValidateAttribute))
            {
                return;
            }

            if (context.ModelState.IsValid)
            {
                return;
            }

            ErrorMessageDto errorMessageDto = new ErrorMessageDto
            {
                ErrorCode = "999999997"
            };

            foreach (var item in context.ModelState)
            {
                if (item.Value.ValidationState != ModelValidationState.Invalid)
                {
                    continue;
                }

                string[] errors = item.Value.Errors.Select(p => p.ErrorMessage).ToArray();

                if (string.IsNullOrWhiteSpace(errorMessageDto.ErrorMessage))
                {
                    errorMessageDto.ErrorMessage = errors.FirstOrDefault();
                }

                errorMessageDto.ErrorDetails.Add(item.Key.ToSnakeCase(), errors);
            }

            context.Result = new ObjectResult(errorMessageDto)
            {
                StatusCode = 400
            };
        }
    }
}